import os
import re
import logging
from pathlib import Path
from typing import List, Dict, Any
from langchain_core.tools import tool

logger = logging.getLogger(__name__)

# 定义工作区路径
WORKSPACE_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), "workspace")

def _get_safe_path(path_str: str) -> Path:
    """确保路径在工作区内"""
    if os.path.isabs(path_str):
        path = Path(path_str)
    else:
        path = Path(WORKSPACE_ROOT) / path_str
    
    if not os.path.exists(WORKSPACE_ROOT):
        os.makedirs(WORKSPACE_ROOT)
    return path

@tool
def split_novel_file(file_path: str) -> Dict[str, Any]:
    """将小说文本文件按章节拆分为多个文件"""
    try:
        input_path = _get_safe_path(file_path)
        if not input_path.exists():
            return {"error": f"找不到文件: {file_path}"}
            
        content = input_path.read_text(encoding='utf-8')
        out_dir = input_path.parent / f"{input_path.stem}_拆解档案"
        chapters_dir = out_dir / "原始章节"
        os.makedirs(chapters_dir, exist_ok=True)
        
        # 匹配 "第X章" 或 "Chapter X"
        # 允许标题前后有空白，允许数字是中文或阿拉伯数字
        pattern = r'(?:^|\n)\s*(?:第[0-9一二三四五六七八九十百千]+[章回节]|Chapter\s*\d+).*'
        matches = list(re.finditer(pattern, content))
        chapter_files = []
        
        if not matches:
            out_file = chapters_dir / "全文.txt"
            out_file.write_text(content, encoding='utf-8')
            chapter_files.append(str(out_file))
        else:
            for i in range(len(matches)):
                start = matches[i].start()
                end = matches[i+1].start() if i < len(matches) - 1 else len(content)
                
                chapter_text = content[start:end].strip()
                if not chapter_text:
                    continue
                    
                # 获取第一行作为标题
                title_line = chapter_text.split('\n')[0].strip()
                # 清理文件名非法字符
                safe_title = re.sub(r'[\\/*?:"<>|]', "", title_line)[:50]
                
                filename = f"{i+1:03d}_{safe_title}.txt"
                file_path = chapters_dir / filename
                file_path.write_text(chapter_text, encoding='utf-8')
                chapter_files.append(str(file_path))
                
        return {
            "success": True,
            "output_dir": str(out_dir),
            "chapter_files": chapter_files
        }
    except Exception as e:
        return {"error": str(e)}

def _ensure_dict(data: Any) -> Dict[str, Any]:
    """确保数据是字典，如果是列表则取第一项"""
    if isinstance(data, list):
        return data[0] if len(data) > 0 and isinstance(data[0], dict) else {}
    return data if isinstance(data, dict) else {}

@tool
def save_chapter_report(output_dir: str, chapter_index: int, chapter_title: str, summary: str) -> Dict[str, Any]:
    """保存单章剧情梗概"""
    try:
        report_dir = Path(output_dir) / "分章详解"
        os.makedirs(report_dir, exist_ok=True)
        
        md = f"# {chapter_title}\n\n## 剧情梗概\n{summary}\n"
        
        safe_title = re.sub(r'[\\/*?:"<>|]', "", chapter_title)[:50]
        filename = f"{chapter_index:03d}_{safe_title}_报告.md"
        (report_dir / filename).write_text(md, encoding='utf-8')
        
        return {"success": True}
    except Exception as e:
        print(f"❌ 保存报告失败: {e}")
        return {"error": str(e)}

@tool
def create_master_guide(output_dir: str, final_analysis: Dict[str, Any]) -> Dict[str, Any]:
    """生成最终人物档案和世界观设定"""
    try:
        base = Path(output_dir)
        
        # 1. 人物档案
        chars_content = "# 人物档案\n\n"
        chars = final_analysis.get('characters', {})
        if isinstance(chars, dict):
            for name, info in chars.items():
                chars_content += f"## {name}\n{info}\n\n"
        else:
            chars_content += str(chars)
            
        (base / "人物档案.md").write_text(chars_content, encoding='utf-8')
        
        # 2. 世界观设定
        world_content = "# 世界观设定\n\n"
        world = final_analysis.get('world_setting', {})
        if isinstance(world, dict):
            for k, v in world.items():
                world_content += f"## {k}\n{v}\n\n"
        else:
            world_content += str(world)
            
        (base / "世界观设定.md").write_text(world_content, encoding='utf-8')
        
        # 3. 语言风格分析
        style_content = "# 语言风格基调\n\n"
        style_content += final_analysis.get('style_analysis', '无')
        (base / "语言风格分析.md").write_text(style_content, encoding='utf-8')
        
        # 4. 结构分析
        structure_content = "# 结构分析\n\n"
        structure = final_analysis.get('structure_analysis', {})
        if isinstance(structure, dict):
            structure_content += f"## 综合剧情结构\n{structure.get('structure_breakdown', '无')}\n\n"
            structure_content += f"## 节奏把控\n{structure.get('pacing', '无')}\n\n"
        else:
            structure_content += str(structure)
            
        (base / "结构分析.md").write_text(structure_content, encoding='utf-8')
        
        return {"success": True}
    except Exception as e:
        return {"error": str(e)}

NovelTools = [split_novel_file, save_chapter_report, create_master_guide]
